<template>
  <tree :list="currentList" :value="currentValue" :multiple="multiple" @input="handleInput" />
</template>


<script>
import { deptAndUserTree } from '@/api/system/dept'
import tree from './tree.vue'

export default {
  data() {
    return {
      depts: []
    }
  },
  components: {
    tree
  },
  props: {
    value: {
      type: [Array, String, Number],
      default: null,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    deptId: {
      type: [String, Number],
      default: 0
    },
  },
  computed: {
    currentList() {
      if (this.deptId) {
        const dept = this.getDept(this.deptId, this.depts);
        if (dept) {
          return [dept];
        }
        return [];
      }
      return this.depts;
    },
    currentValue() {
      if (this.multiple) {
        return this.value || [];
      }
      return this.value || '';
    },
  },
  mounted() {
    this.deptAndUserTree();
  },
  methods: {
    getDept(deptId, children = this.depts) {
      for (let index = 0; index < children.length; index++) {
        const dept = children[index];
        if (dept.deptId === deptId) {
          return dept;
        }
        if (dept.children && dept.children.length > 0) {
          const foundDept = this.getDept(deptId, dept.children);
          if (foundDept !== null) {
            return foundDept; // 在孙部门中找到匹配项时返回
          }
        }
      }
      return null;
    },
    async deptAndUserTree() {
      const res = await deptAndUserTree();
      this.depts = res.data;
    },
    handleInput(newValue) {
      this.$emit("input", newValue);
    },
  }
}
</script>